﻿using System;
using System.Collections.Generic;
using System.Linq;

using AMC.SubstitutionCache.Models;

using Orchard;
using Orchard.Caching;
using Orchard.ContentManagement;
using Orchard.OutputCache.Models;

namespace AMC.SubstitutionCache.Services
{
    public class SubstitutionSettings : ISubstitutionSettings
    {
        private readonly ICacheManager _cacheManager;
        private readonly ISignals _signals;
        private readonly IWorkContextAccessor _workContextAccessor;

        public SubstitutionSettings(IWorkContextAccessor workContextAccessor, ICacheManager cacheManager, ISignals signals)
        {
            _workContextAccessor = workContextAccessor;
            _cacheManager = cacheManager;
            _signals = signals;
        }


        public ISet<string> ExcludedShapeTypes
        {
            get
            {
                return _cacheManager.Get("SubstitutionCacheSettingsPart.ExcludedShapeTypes", context =>
                {
                    context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                    var types = _workContextAccessor.GetContext()
                            .CurrentSite.As<SubstitutionCacheSettingsPart>()
                            .ExcludedShapeTypes;

                    if (string.IsNullOrEmpty(types))
                        return new HashSet<string>();

                    return new HashSet<string>(types.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                        .Select(t => t.Trim())
                        .Distinct());
                });
            }
        }

        public TimeSpan DefaultCacheDuration
        {
            get
            {
                return _cacheManager.Get("SubstitutionCacheSettingsPart.Duration", context =>
                {
                    context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                    var seconds = _workContextAccessor.GetContext()
                            .CurrentSite.As<SubstitutionCacheSettingsPart>()
                            .DefaultCacheDurationSeconds;

                    return TimeSpan.FromSeconds(seconds);
                });
            }
        }
    }
}